package com.wish.g04.business.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wish.g04.base.entity.*;
import com.wish.g04.business.mapper.UsersMapper;
import com.wish.g04.base.service.*;
import com.wish.g04.business.dto.BusinessDTO;
import com.wish.g04.business.dto.UserDTO;
import com.wish.g04.business.mapper.RoleMapper;
import com.wish.g04.business.service.BusinessService;
import com.wish.g04.business.service.UserService;
import com.wish.g04.business.vo.BusinessVO;
import com.wish.g04.business.vo.RegionVO;
import com.wish.g04.common.core.web.controller.BaseController;
import com.wish.g04.common.core.web.domain.AjaxResult;
import com.wish.g04.common.core.web.page.TableDataInfo;
import com.wish.g04.common.redis.service.RedisService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * author: xuekai
 */

@Service
public class TbBusinessServiceImpl extends BaseController implements BusinessService {

    @Autowired
    private IBusinessService iBusinessService;

    @Autowired
    private IRegionService iRegionService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private UserService userService;

    @Autowired
    private IMCompanyAccountService imCompanyAccountService;

    @Autowired
    private IDeptService iDeptService;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UsersMapper userMapper;

    @Autowired
    private BusinessService businessService;

    @Autowired
    private RedisService redisService;

    //公寓审核--通过--维数公寓
    public static final String EXAMINE_SUCCESS_B = "SMS_132990805";
    //公寓审核--失败--维数公寓
    public static final String EXAMINE_ERROR_B = "SMS_132995754";

    private final String cache="phone:";


    /**
     * 商户列表
     * @return
     */
    @Override
    public TableDataInfo getBusinessList() {
        List<Business> list = iBusinessService.list();

        TableDataInfo dataTable = getDataTable(list);
        List<Business> rows = (List<Business>) dataTable.getRows();
        List<BusinessVO> businessVOS = setBusiness(rows);
        dataTable.setRows(businessVOS);
        return dataTable;
    }

    /**
     * 根据id查询商户信息
     * @param id
     * @return
     */
    @Override
    public BusinessVO selectTbBusinessById(Long id) {
        //根据id查询
        Business business = iBusinessService.getById(id);
        return setBusiness1(business);
    }

    /**
     * 审核
     * @param business
     */
    @Override
    public void notUpdateBusiness(Business business) {
        //修改商户表
        iBusinessService.updateById(business);

        //设置用户信息
        User user = new User();
        user.setApprovalFlag(business.getStatus());
        user.setUserId(Long.valueOf(business.getUserId()));



        //添加企业信息
        if(business.getStatus()==1){
            MCompanyAccount mCompanyAccount = new MCompanyAccount();
            mCompanyAccount.setBusinessId(new Long(business.getId()));
            mCompanyAccount.setBusinessName(business.getName());
            mCompanyAccount.setAccountState(true);
            mCompanyAccount.setCreateUserid(user.getUserId());
            mCompanyAccount.setCreateTime(LocalDateTime.now());
            mCompanyAccount.setUpdateUserid(user.getUserId());
            mCompanyAccount.setUpdateTime(LocalDateTime.now());
            imCompanyAccountService.save(mCompanyAccount);
        }

        //更改用户状态
        iUserService.updateById(user);
        //查询用户信息(短信用到)
        //User userInfo = iUserService.getById(business.getUserId());
    }

    /**
     * 根据id查询商户
     * @param id
     * @return
     */
    @Override
    public Business getById(Long id) {
        return iBusinessService.getById(id);
    }

    /**
     * 商户审核通过
     * @param businessDTO
     * @return
     */
    @Override
    public AjaxResult update(BusinessDTO businessDTO) {

        //根据商户id查询部门,判断是否具有部门
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("business_id",businessDTO.getId());
        List<Dept> deptList = iDeptService.list(queryWrapper);
        if(CollectionUtils.isEmpty(deptList) && deptList.size()==0){
            return AjaxResult.error("请在部门下添加商户");
        }

        //根据部门id查询角色
        Long deptId = deptList.get(0).getDeptId();
        HashMap<String, Object> map = new HashMap<>();
        map.put("businessId",businessDTO.getId());
        map.put("deptId",deptId);
        List<Role> roleList=roleMapper.queryList(map);
        if(CollectionUtils.isEmpty(roleList) && roleList.size()==0){
            return AjaxResult.error("请在角色下添加商户角色");
        }

        //根据部门id和商户id查询用户
        List<User> userList=userMapper.queryList(map);
        if(CollectionUtils.isEmpty(userList) && userList.size()==0){
            return AjaxResult.error("请在用户下添加商户用户");
        }

        //处理用户
        List<Long> roleIdList = roleList.stream().map(role -> role.getRoleId()).collect(Collectors.toList());
        User user = userList.get(0);
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user,userDTO);
        userDTO.setRoleIdList(roleIdList);
        userDTO.setApprovalFlag(1);
        userService.updateUser(userDTO);

        //处理审核
        Business businessInfo=businessService.getById(businessDTO.getId());
        businessInfo.setStatus(1);
        businessService.notUpdateBusiness(businessInfo);
        return AjaxResult.success();
    }

    /**
     * 注册
     * @param userDTO
     * @return
     */
    @Override
    public AjaxResult register(UserDTO userDTO) {
        //判断验证码是否正确
        String key = String.format(cache + userDTO.getMobile());
        String cacheObject = redisService.getCacheObject(key);
        if(cacheObject.equals(userDTO.getCode())){
            return AjaxResult.error("验证码错误");
        }
        redisService.deleteObject(key);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",userDTO.getMobile());
        User user = iUserService.getOne(queryWrapper);
        if(user!=null){
            return AjaxResult.error("手机号已经存在");
        }
        boolean save = iUserService.save(userDTO);
        if(save){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @Override
    public AjaxResult getCityList() {
        List<Region> regionList = iRegionService.list();
        ArrayList<RegionVO> regionVOS = new ArrayList<>();
        regionList.forEach(region -> {
            RegionVO regionVO = new RegionVO();
            BeanUtils.copyProperties(region,regionVO);
            regionVOS.add(regionVO);
        });
        //过滤出省
        List<RegionVO> provinceList = regionVOS.stream().filter(regionVO -> Objects.equals(regionVO.getParentId(), 1)).collect(Collectors.toList());
        provinceList.forEach(province->province.setRegionVOList(getRegionVoList(province.getRegionId(),regionVOS)));
        return AjaxResult.success(provinceList);
    }

    @Override
    public AjaxResult save(BusinessDTO businessDTO) {
        if(!redisService.setCacheLock(businessDTO.getUuid())){
            return AjaxResult.error("重复提交");
        }
        Business business = new Business();
        BeanUtils.copyProperties(businessDTO,business);
        return AjaxResult.success(iBusinessService.save(business));
    }

    /**
     * 获取城市子级
     * @param regionId
     * @param regionVOS
     * @return
     */
    private List<RegionVO> getRegionVoList(Integer regionId, ArrayList<RegionVO> regionVOS) {
        List<RegionVO> provinceList = regionVOS.stream().filter(regionVO -> Objects.equals(regionVO.getParentId(), regionId)).collect(Collectors.toList());
        /*List<RegionVO> collect = provinceList.stream().filter(province -> Objects.equals(province.getRegionLevel(), 3)).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(collect)){
            return collect;
        }*/
        provinceList.forEach(province->province.setRegionVOList(getRegionVoList1(province.getRegionId(),regionVOS)));
        return provinceList;


    }

    /**
     *
     * @param regionId
     * @param regionVOS
     * @return
     */
    private List<RegionVO> getRegionVoList1(Integer regionId, ArrayList<RegionVO> regionVOS) {
        List<RegionVO> provinceList = regionVOS.stream().filter(regionVO -> Objects.equals(regionVO.getParentId(), regionId)).collect(Collectors.toList());
        return provinceList;
    }

    /**
     * 详情设置属性
     * @param business
     * @return
     */
    private BusinessVO setBusiness1(Business business) {
        BusinessVO businessVO = new BusinessVO();
        BeanUtils.copyProperties(business,businessVO);
        //设置省市县,管理员
        businessVO.setProvinceName(iRegionService.getById(business.getProvince()).getRegionName());
        businessVO.setCityName(iRegionService.getById(business.getCity()).getRegionName());
        businessVO.setCountyName(iRegionService.getById(business.getCounty()).getRegionName());
        businessVO.setUserName(iUserService.getById(business.getUserId()).getUsername());
        return businessVO;
    }

    /**
     * 列表设置属性
     * @param list
     */
    private List<BusinessVO> setBusiness(List<Business> list) {
        //转vo对象
        ArrayList<BusinessVO> arrayList = new ArrayList<>();
        list.forEach(business -> {
            BusinessVO businessVO = new BusinessVO();
            BeanUtils.copyProperties(business,businessVO);
            arrayList.add(businessVO);
        });

        //取出省市县id集合
        List<Integer> provinceIdList = list.stream().map(business -> business.getProvince()).collect(Collectors.toList());
        List<Integer> cityIdList = list.stream().map(business -> business.getCity()).collect(Collectors.toList());
        List<Integer> countyIdList = list.stream().map(business -> business.getCounty()).collect(Collectors.toList());

        //查出省市县
        List<Region> provinceList = iRegionService.listByIds(provinceIdList);
        List<Region> cityList = iRegionService.listByIds(cityIdList);
        List<Region> countyList = iRegionService.listByIds(countyIdList);

        //设置省
        for (int i = 0; i < provinceList.size(); i++) {
            BusinessVO businessVO = arrayList.get(i);
            businessVO.setProvinceName(provinceList.get(i).getRegionName());
        }

        //设置市
        for (int i = 0; i < cityList.size(); i++) {
            BusinessVO businessVO = arrayList.get(i);
            businessVO.setCityName(cityList.get(i).getRegionName());
        }

        //设置县
        for (int i = 0; i < countyList.size() ; i++) {
            BusinessVO businessVO = arrayList.get(i);
            businessVO.setCountyName(countyList.get(i).getRegionName());
        }

        List<Integer> userIdList = list.stream().map(business -> business.getUserId()).collect(Collectors.toList());
        List<User> userList = iUserService.listByIds(userIdList);

        //设置管理员
        for (int i = 0; i < userList.size(); i++) {
            BusinessVO businessVO = arrayList.get(i);
            businessVO.setUserName(userList.get(i).getUsername());
        }
        return arrayList;
    }
}
